package com.demo.drools.dal.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.demo.drools.rules.config.BaseCouponRuleConfig;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author ZhouSicheng
 * @description
 * @date 2019/3/15 16:24
 */
@MappedJdbcTypes(JdbcType.VARCHAR)
public class OfferConfigHandler extends BaseTypeHandler<BaseCouponRuleConfig> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, BaseCouponRuleConfig parameter, JdbcType jdbcType) throws SQLException {
        ps.setString(i, JSON.toJSONString(parameter, SerializerFeature.WriteClassName));
    }

    @Override
    public BaseCouponRuleConfig getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String s = rs.getString(columnName);
        return convertToEntityAttribute(s);
    }

    @Override
    public BaseCouponRuleConfig getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String s = rs.getString(columnIndex);
        return convertToEntityAttribute(s);
    }

    @Override
    public BaseCouponRuleConfig getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String s = cs.getString(columnIndex);
        return convertToEntityAttribute(s);
    }

    private BaseCouponRuleConfig convertToEntityAttribute(String s) {
        return JSON.parseObject(s, BaseCouponRuleConfig.class);
    }
}
